#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: kindey
@Date: 2025/8/7
@Description:
"""
from typing import List
from datetime import datetime, timedelta
import logging

from apps.serializers.dev_data_serializer import TDevDataSerializer
from apps.repositories import TDevDataRepository
from apps.repositories.data_repository import DataRepository
from apps.plugin.AbnormalDataFiltering import AbnormalDataFiltering
from apps.plugin.DataAlignment import DataAlignment


class DevDataService:
    """
    DevData 业务逻辑服务类
    """
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    def __init__(self):
        self.dev_data_repository = TDevDataRepository()

    def create_dev_data(self, data_type, data_id, dev_id, reg_id, data_value, data_time):
        """
        创建设备数据记录的业务逻辑
        """
        # 可以在这里添加业务逻辑校验
        if not data_type or len(data_type) > 3:
            raise ValueError("data_type不能为空且长度不能超过3")

        if data_value is None:
            raise ValueError("data_value不能为空")

        return self.dev_data_repository.create_dev_data(
            data_type=data_type,
            data_id=data_id,
            dev_id=dev_id,
            reg_id=reg_id,
            data_value=data_value,
            data_time=data_time
        )

    def get_dev_data_by_id(self, pk):
        """
        根据ID获取设备数据记录
        """
        return self.dev_data_repository.get_dev_data_by_id(pk)

    def get_all_dev_data(self):
        """
        获取所有设备数据记录
        """
        return self.dev_data_repository.get_all_dev_data()

    def update_dev_data(self, pk, **kwargs):
        """
        更新设备数据记录的业务逻辑
        """
        # 可以在这里添加业务逻辑校验
        if 'data_type' in kwargs and (not kwargs['data_type'] or len(kwargs['data_type']) > 3):
            raise ValueError("data_type不能为空且长度不能超过3")

        return self.dev_data_repository.update_dev_data(pk, **kwargs)

    def delete_dev_data(self, pk):
        """
        删除设备数据记录的业务逻辑
        """
        # 可以在这里添加业务逻辑校验，例如权限检查等
        return self.dev_data_repository.delete_dev_data(pk)

    def get_dev_data_by_condition(self, data_type, dev_id, start_time, end_time):
        """
        根据条件获取设备数据记录

        :param data_type 数据类型，空：原始数据，iqr：IQR筛选后的数据，zsc：Z-score数据过滤后的数据，rec：对齐后数据
        :param dev_id 设备id
        :param start_time 开始时间
        :param end_time 结束时间
        """
        queryset = self.dev_data_repository.get_dev_data_by_condition(
            data_type=data_type,
            dev_id=dev_id,
            start_time=start_time,
            end_time=end_time
        )
        # 使用 TDevDataSerializer 序列化查询结果
        serializer = TDevDataSerializer()
        return serializer.serialize_list(queryset)

class DevDataAnalysisService:
    """
    DevData 数据过滤、数据对齐服务类
    """
    def __init__(self):
        self.dev_data_repository = TDevDataRepository()
        self.data_repository = DataRepository()

    def analysis_one_dev_datas(self,dev_id, start_time, end_time, space):
        """
        处理单个设备的数据

        :param dev_id 设备id
        :param start_time 开始时间
        :param end_time 结束时间
        :param space 间隔时间，单位秒
        """
        z_score_threshold = 3
        dev_data_list = self.data_repository.get_device_data_with_joins(dev_id)
        for data in dev_data_list:
            self.dev_data_repository.create_dev_data(
                "",data.id,dev_id,data.reg_id,data.data_value,data.data_time
            )

        iqr_dev_data = AbnormalDataFiltering.iqr_filtering(dev_data_list)
        for data in iqr_dev_data:
            self.dev_data_repository.create_dev_data(
                "iqr",data.id,dev_id,data.reg_id,data.data_value,data.data_time
            )

        z_score_dev_data = AbnormalDataFiltering.z_score_filtering(iqr_dev_data,z_score_threshold)
        for data in z_score_dev_data:
            self.dev_data_repository.create_dev_data(
                "zsc",data.id,dev_id,data.reg_id,data.data_value,data.data_time
            )

        s_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        e_time = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        time_delta = timedelta(seconds=space)
        aligned_dev_date = DataAlignment.reacquisition_by_time(z_score_dev_data, s_time, e_time, time_delta)
        for data in aligned_dev_date:
            self.dev_data_repository.create_dev_data(
                "rec",data.id,dev_id,data.reg_id,data.data_value,data.data_time
            )
    def analysis_dev_datas(self,dev_ids: List[int], start_time, end_time, space):
        for dev_id in dev_ids:
            self.analysis_one_dev_datas(dev_id,start_time,end_time,space)
